package com.example.financeapi.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Alvin
 * @description 基于注解的@Scheduled默认为单线程，开启多个定时任务时需配置，使Spring Task多线程异步执行方式生效
 */
@Configuration
@ComponentScan({"com.example.financeapi.service.impl","com.example.financeapi.job"})
@EnableAsync //利用@EnableAsync注解开启异步任务支持
public class AsyncTaskConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //配置线程池中的线程的名称前缀
        taskExecutor.setThreadNamePrefix("finance-task-");
        //配置核心线程数
        taskExecutor.setCorePoolSize(5);
        //配置最大线程数
        taskExecutor.setMaxPoolSize(20);
        //线程池所使用的缓冲队列 设置队列大小
        taskExecutor.setQueueCapacity(25);
        //等待任务在关机时完成--表明等待所有线程执行完优雅关闭线程池
        taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        //等待时间 （默认为0，此时立即停止），并没等待xx秒后强制停止
        //taskExecutor.setAwaitTerminationSeconds(60);
        //配置线程任务超时时间
        taskExecutor.setKeepAliveSeconds(1800);
        //配置拒绝策略，满了之后等待的策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}
